package com.pdsu.alumni.config.shiro;

import com.pdsu.alumni.common.annotation.NoAuthentication;
import com.pdsu.alumni.config.SpringContextBean;
import com.pdsu.alumni.pojo.User;
import com.pdsu.alumni.service.UserService;
import com.pdsu.alumni.util.Constant;
import com.pdsu.alumni.util.JwtComponent;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;

public class JWTFilter extends BasicHttpAuthenticationFilter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JwtComponent jwtComponent;
    @Autowired
    private UserService userService;

    /**
     * 判断用户是否想要登入。 检测header里面是否包含Authorization字段即可
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader("Authorization");
        String url = req.getRequestURI();
        if (url.equals("/auth/login")) {
            return false;
        }
        return authorization != null;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JWTToken token = new JWTToken(authorization);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(token);
        // 如果没有抛出异常则代表登入成功，返回true
        setUserBean(request, response, token);
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        response401(request, response);
        return false;
    }


    /**
     * 这里进行一波说明,不知道为什么,所有的请求都会进入这边进行登录,走executeLogin,
     * 前面的过滤器放行了个寂寞,
     * 回头再处理,但是我们又需要把一些请求进行放行,不验证登录,所以临时造了个注解进行跳过登陆验证
     * 当检测到方法有NoAuthentication时,我们进行一波放行
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            /******注解调用如下******/
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            WebApplicationContext ctx = RequestContextUtils.findWebApplicationContext(httpServletRequest);
            RequestMappingHandlerMapping mapping = ctx.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
            HandlerExecutionChain handler = null;
            try {
                handler = mapping.getHandler(httpServletRequest);
                Annotation[] declaredAnnotations = ((HandlerMethod) handler.getHandler()).getMethod().getDeclaredAnnotations();
                if (declaredAnnotations.length != 0) {
                    for (Annotation annotation : declaredAnnotations) {
                        /**
                         *如果含有注解，则认为是不需要验证是否登录，
                         *直接放行即可
                         **/
                        if (NoAuthentication.class.equals(annotation.annotationType())) {
                            return true;
                        }
                    }
                }
                /*******注解调用如上*******/
                // 执行登录
                executeLogin(request, response);
                Subject subject = getSubject(request, response);
                String[] perms = (String[]) mappedValue;
                boolean isPermitted = true;
                if (perms != null && perms.length > 0) {
                    if (perms.length == 1) {
                        if (!subject.isPermitted(perms[0])) {
                            isPermitted = false;
                        }

                    } else if (!subject.isPermittedAll(perms)) {
                        isPermitted = false;
                    }

                }
                return isPermitted;
            } catch (Exception e) {
                e.printStackTrace();
                responseTimeOut(request, response);
            }
        }
        return true;
    }

    private void setUserBean(ServletRequest request, ServletResponse response, JWTToken token) {
        if (this.userService == null) {
            this.userService = SpringContextBean.getBean(UserService.class);
        }
        String userAccount = jwtComponent.getUserAccount(String.valueOf(token.getCredentials()));
        User userBean = userService.queryUserByAccount(userAccount);
        request.setAttribute("currentUser", userBean);
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers",
                httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        for (String urlMethod : Constant.METHOD_URL_SET) {
            String[] split = urlMethod.split(":");
            if (split[0].equals(httpServletRequest.getRequestURI())
                    && (split[1].equals(httpServletRequest.getMethod()) || "RequestMapping".equals(split[1]))) {
                return true;
            } else if (split[0].contains("{")) {
                String uri = split[0].substring(0, split[0].indexOf("{"));
                if (httpServletRequest.getRequestURI().startsWith(uri)) {
                    return true;
                }
            }
        }
        return super.preHandle(request, response);
    }

    /**
     * 将非法请求跳转到 /401
     */
    private void response401(ServletRequest req, ServletResponse resp) {
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
            //httpServletResponse.sendRedirect("/auth/401");
            httpServletResponse.sendError(401);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 超时跳转到 /timeout
     */
    private void responseTimeOut(ServletRequest req, ServletResponse resp) {
//        try {
//            HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
//            //httpServletResponse.sendRedirect("/auth/401");
//            httpServletResponse.sendError(403);
//        } catch (IOException e) {
//            logger.error(e.getMessage());
//        }
    }
}
